<template>
  <el-col>
    <el-tree
      :node-contextmenu="clickRight"
      :data="orgData"
      :show-checkbox="showCheckbox"
      node-key="value"
      :default-expand-all="true"
      :expand-on-click-node="false"
      :props="defaultProps"
    >
      <span
        class="custom-tree-node"
        slot-scope="{ node, data }"
        @mouseenter="mouseenter(data)"
        @mouseleave="mouseleave(data)"
      >
        <span>{{ node.label }}</span>
        <span class="custom-tree-node-btn" v-if="showOperateBtn">
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => upRemove(data, node)"
            >上移</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => downRemove(data, node)"
            >下移</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => add(data)"
            >新增</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => rename(data)"
            >更名</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            class="fontRed"
            v-if="data.isSys !== 1"
            @click="() => del(data, orgData)"
            >删除</el-button
          >
        </span>
      </span>
    </el-tree>
    <DownloadIdentify
      @cancel="cancel"
      @update="dialogSubmit"
      :visible.sync="dialogVisible"
      title="新增分类"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="级别" prop="floor">
          <el-select
            v-model="ruleForm.floor"
            placeholder="级别"
            style="width: 400px"
          >
            <el-option label="本级" value="1"></el-option>
            <el-option label="下级" v-if="showNextLevel" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="typeName">
          <el-input
            v-model.trim="ruleForm.typeName"
            maxlength="10"
            style="width: 400px"
          ></el-input>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
    <DownloadIdentify
      @cancel="cancel"
      @update="renameSubmit"
      :visible.sync="updateNamedialogVisible"
      title="分类更名"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="typeName">
          <el-input
            v-model.trim="ruleForm.typeName"
            maxlength="10"
            style="width: 400px"
          ></el-input>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </el-col>
</template>

<script>
import DownloadIdentify from "@/components/FormDialog";
import { mapState, mapMutations } from "vuex";
export default {
  components: { DownloadIdentify },
  props: ["showCheckbox", "showOperateBtn", "tableData"],
  data() {
    return {
      showNextLevel: true,
      dialogVisible: false,
      updateNamedialogVisible: false,
      orgData: [],
      currentNode: "",
      ruleForm: {
        typeName: "",
        level: "",
        parentId: "",
      },
      rules: {
        typeName: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        floor: [{ required: true, message: "请选择分类级别", trigger: "blur" }],
      },
      defaultProps: {
        children: "children",
        label: "label",
        is_show: true,
      },
    };
  },
  mounted() {
    this.getList();
  },
  computed: {
    ...mapState(["system_deviceCategory", "app"]),
  },
  methods: {
    async getList() {
      // 获取最新的排序
      await this.$store.dispatch("app/getCodeList", ["assetType"]); //code转码
      // 刷新
      this.orgData = this.$store.state.app.allCode.assetType;
    },
    clickRight(event, data, node, self) {
      console.log(data);
    },
    mouseenter(data) {
      this.$set(data, "show", true);
    },
    mouseleave(data) {
      this.$set(data, "show", false);
    },
    dialogSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          switch (this.ruleForm.floor) {
            case "1":
              // 新建本级
              this.ruleForm.parentId = this.currentNode.parentId;
              this.ruleForm.level = this.currentNode.level;
              break;
            case "2":
              // 新建下级
              this.ruleForm.parentId = this.currentNode.id;
              this.ruleForm.level = this.currentNode.level + 1;
              break;
            default:
              break;
          }

          this.$store
            .dispatch("system_deviceCategory/saveCategoryInfo", this.ruleForm)
            .then((res) => {
              this.dialogVisible = false;
              this.getList();
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    renameSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 修改名称
          const { typeName } = this.ruleForm;
          const ruleForm = { ...this.currentNode, typeName };

          this.$store
            .dispatch("system_deviceCategory/saveCategoryInfo", ruleForm)
            .then((res) => {
              this.updateNamedialogVisible = false;
              this.getList();
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.updateNamedialogVisible = false;
      // this.$router.go(0);
      this.ruleForm = {
        typeName: "",
        level: "",
        parentId: "",
      };
    },
    //五个操作方法 上移下移删除添加更名
    //新增
    add(e) {
      this.ruleForm = {
        typeName: "",
        level: "",
        parentId: "",
      };
      console.log(e);
      this.showNextLevel = e.parentId == 0;
      this.currentNode = e;
      this.dialogVisible = true;
    },
    //更名
    rename(e) {
      this.currentNode = e;
      this.ruleForm.typeName = e.label;

      this.updateNamedialogVisible = true;
    },
    //删除
    del(row, orgData) {
      console.log(row, "+++++row delete++++");
      console.log(orgData, "++++orgData+++");
      if (orgData.length == 1 && row.level == 1) {
        this.$message({
          type: "error",
          message: "企业设备分类不可为空",
        });
        return;
      }
      this.$confirm(
        `确认删除该分类？请先确保：
<br />
1.该分类无下级分类
<br />
2.该分内内无设备`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true,
        }
      )
        .then(() => {
          this.$store
            .dispatch("system_deviceCategory/deleteDeviceInfo", row.id)
            .then((response) => {
              // this.$message({
              //   type: "success",
              //   message: "删除成功!"
              // });
              // this.dialogVisible=true
              this.getList();
            })
            .catch(() => {
              // this.$message({
              //   type: "info",
              //   message: "删除失败"
              // });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //上移
    async upRemove(e, n) {
      if (!n.previousSibling) {
        return this.$message({
          type: "info",
          message: "已是第一项",
        });
      }

      this.currentNode = e;
      await this.$store.dispatch("system_deviceCategory/sortDepartmentInfo", [
        e,
        n.previousSibling.data,
      ]);
      // 刷新数据
      this.getList();
    },
    //下移
    async downRemove(e, n) {
      if (!n.nextSibling) {
        return this.$message({
          type: "info",
          message: "已是最后一项",
        });
      }

      this.currentNode = e;
      await this.$store.dispatch("system_deviceCategory/sortDepartmentInfo", [
        e,
        n.nextSibling.data,
      ]);
      // 刷新数据
      this.getList();
    },
    renderContent(h, { node, data, store }) {
      if (node.highlight) {
        return (
          <span class="custom-tree-node">
            <span style="color:blue">{node.label}</span>
          </span>
        );
      } else {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
          </span>
        );
      }
    },
  },
};
</script>
<style lang="scss">
.el-tree {
  background: #f6f8fa;
}
.custom-tree-node-btn {
  margin-left: 15px;
  font-size: 12px;
}
</style>
